package com.gui.juc.cas;

import cn.hutool.core.util.RandomUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
public class CasDemo1 {

    private static final AtomicInteger atomicInteger = new AtomicInteger(1000);

    public static void main(String[] args) {


        ExecutorService threadPool = Executors.newFixedThreadPool(10);
        List<Future<Integer>> futureList = new ArrayList<>();


        for (int i = 0; i < 600; i++) {
            Future<Integer> future = threadPool.submit(() -> {
                int count = atomicInteger.get();
                int wantBuyCount = 2;
                if (count >= wantBuyCount) {
                    atomicInteger.getAndAdd(wantBuyCount * (-1));
                    return wantBuyCount;
                } else {
                    log.debug("没票了");
                    return 0;
                }
            });
            futureList.add(future);
        }

        Integer result = 0;
        try {
            for (Future<Integer> future : futureList) {
                result += future.get();
            }
        } catch (Exception e) {
            log.error("error:", e);
        }
        threadPool.shutdown();
        log.debug("卖出的票：{}", result);
        log.debug("剩余的票：{}", atomicInteger.get());
    }

    public static void testCas(){


        ExecutorService threadPool = Executors.newFixedThreadPool(10);
        List<Future<Integer>> futureList = new ArrayList<>();

        atomicInteger.getAndIncrement();

        for (int i = 0; i < 600; i++) {
            Future<Integer> future = threadPool.submit(() -> {
                while (true) {
                    int count = atomicInteger.get();
                    int wantBuyCount = 2;
                    if (count >= wantBuyCount) {
                        boolean success = atomicInteger.compareAndSet(count, count - wantBuyCount);
                        if (success) {
                            return wantBuyCount;
                        }
                        log.debug("不行啊 重试。。。");
                    } else {
                        log.debug("没票了");
                        return 0;
                    }
                }
            });
            futureList.add(future);
        }

        Integer result = 0;
        try {
            for (Future<Integer> future : futureList) {
                result += future.get();
            }
        } catch (Exception e) {
            log.error("error:", e);
        }
        threadPool.shutdown();
        log.debug("卖出的票：{}", result);
        log.debug("剩余的票：{}", atomicInteger.get());
    }
}
